package com.c611.smartclassroom.controller;

import com.c611.smartclassroom.component.LogHandlerInterceptor;
import com.c611.smartclassroom.mapper.LogMapper;
import com.c611.smartclassroom.mapper.UserMapper;
import com.c611.smartclassroom.model.Log;
import com.c611.smartclassroom.model.User;
import com.c611.smartclassroom.model.UserExample;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 登陆界面的方法
 */
@RestController
@RequestMapping("/login")
public class LoginController {

    @Autowired
    UserMapper userMapper;

    @Autowired
    LogMapper logMapper;

//    Map<Integer,HttpSession> sessionMap = new HashMap<>();

    /**
     * 验证码字符串的方法
     */
    @PostMapping("/imgCode")
    public String[] imgCode(HttpSession session) {
        String[] imgCode = new String[4];
        String aScode = "A,B,C,E,F,G,H,J,K,L,M,N,P,Q,R,S,T,W,X,Y,Z,1,2,3,4,5,6,7,8,9,0";
        String[] aCode = aScode.split(",");
        //抽四个随机数
        Random random = new Random(System.currentTimeMillis());
        for(int i = 0;i < 4;i++) {
            if(random.nextInt(2) == 1) {
                imgCode[i] = aCode[random.nextInt(aCode.length)].toLowerCase();
            }else {
                imgCode[i] = aCode[random.nextInt(aCode.length)];
            }
        }
//        System.out.println(session.getId());
//        System.out.println("imgCode = " + imgCode[0] + imgCode[1] + imgCode[2] + imgCode[3]);
        //将验证码存入当前的session中
        session.setAttribute("imgCode",imgCode[0] + imgCode[1] + imgCode[2] + imgCode[3] + "");
        return imgCode;
    }

    /**
     * 退出系统的方法
     */
    @PostMapping("/logout")
    public void logout(HttpServletRequest request) {
        HttpSession session = request.getSession();
        Object obj = session.getAttribute("loginUser");
//        System.out.println(obj);
        if(obj != null) {
            //1、写入退出日志
            User user = (User)obj;
            Date requestTime = new Date();
            Log log = new Log();
            log.setOperator(user.getUserrealname());
            log.setOpdescribe("退出");
            log.setOpermethod("logout");
            log.setOpaddress(LogHandlerInterceptor.getIpAddr(request));
            log.setOpertime(requestTime);
            logMapper.insertSelective(log);
            session.removeAttribute("loginUser");
        }
    }

    /**
     * 登陆方法
     */
    @PostMapping("/login")
    public int login(@RequestParam("username") String username, @RequestParam("password") String password, @RequestParam("code") String code, HttpServletRequest request) {
        if(username == null || username.isEmpty() ||  password == null || password.isEmpty() || code == null || code.isEmpty()) return 0;
        HttpSession session = request.getSession();
        //校验验证码
         String imgCode = (String) session.getAttribute("imgCode");
         if(imgCode == null || !imgCode.equals(code)) return 0;
         //校验手机号码
        Pattern p = Pattern.compile("^[1][3,4,5,7,8][0-9]{9}$"); // 验证手机号
        Matcher m = p.matcher(username);
        if(!m.matches()) return 0;
        //参数都检验完了，查询数据库
        UserExample userExample = new UserExample();
        userExample.createCriteria()
                .andUsertelEqualTo(username)
                .andDelflagEqualTo(0);
        List<User> list = userMapper.selectByExample(userExample);
        if(list.size() == 0) return 0;
        User user = list.get(0);
        //打印出加密后的密码来
//        System.out.println("我是后台 = " + DigestUtils.md5DigestAsHex(user.getUserpwd().getBytes()));
//        System.out.println("我是前台 = " + password);
//        if(!password.equals(DigestUtils.md5DigestAsHex(user.getUserpwd().getBytes()))) return 0;
        if(!password.equals(user.getUserpwd())) return 0;

        //将登陆信息存入session中
        session.setAttribute("loginUser",user);

        //写入登陆日志

        Date requestTime = new Date();
        Log log = new Log();
        log.setOperator(user.getUserrealname());
        log.setOpdescribe("登陆");
        log.setOpermethod("login");
//        System.out.println("ip = " + LogHandlerInterceptor.getIpAddr(request));
        log.setOpaddress(LogHandlerInterceptor.getIpAddr(request));
        log.setOpertime(requestTime);
        logMapper.insertSelective(log);
        return 1;

      /*  //查看当前用户的id是否进行了重新登陆
        if(sessionMap.get(user.getUserid()) == null) {
            //说明是首次登陆
            //将登陆信息存入session中
            session.setAttribute("loginUser",user);
            sessionMap.put(user.getUserid(),session);
            return 1;
        }else {
            HttpSession oldSession = sessionMap.get(user.getUserid());
            oldSession.invalidate();    //使旧session过期
            //存入新session
            sessionMap.remove(user.getUserid());
            session.setAttribute("loginUser",user);
            sessionMap.put(user.getUserid(),session);
            return 1;
        }*/
    }
}
